<style>
    #notice-edit {
        padding: 20px 25px 25px 0;
    }

    img[src=""], img:not([src]) {

        opacity: 0;

    }

</style>

<div class="layui-fluid" id="notice-edit">
    <form class="layui-form" action="" lay-filter="notice-edit-form" id="editForm">
        <div class="layui-form-item">
            <label class="layui-form-label febs-form-item-require">通知图片</label>
            <div class="layui-upload-list">
                <img id="imgNotice"  class="layui-upload-img" width="35%" style="vertical-align: bottom">
                <a onclick="getElementById('imgNotice').click()">上传图片</a>
                <input type="hidden" id="notimg" name="imgUrl">
                <p id="demoText"></p>
            </div>
            <span style="padding-left: 110px;font-size: 13px;">（点击图片进行上传，上传的图片大小应小于750*560）</span>

        </div>
        <div class="layui-form-item">
            <label class="layui-form-label febs-form-item-require">通知标题</label>
            <div class="layui-input-block">
                <input type="text" id="txtTitle" name="title" minlength="2"
                       maxlength="50"
                       autocomplete="off" class="layui-input" lay-verify="required">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">公司名</label>
            <div class="layui-input-block">
                <input type="text" id="txtCompany" data-th-value="陕西全务" minlength="4" maxlength="100"
                       autocomplete="off" class="layui-input" disabled="true" readonly="true">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">创建人</label>
            <div class="layui-input-block">
                <input type="text" id="txtCreateUser" name="username" data-th-value="${noticeName}" minlength="2"
                       maxlength="100"
                       autocomplete="off" class="layui-input" disabled="true" readonly="true">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">创建日期</label>
            <div class="layui-input-block">
                <input type="text" data-th-value="${createDateTime}" disabled="true" name="createTime"
                       id="txtCreateTime" minlength="4" maxlength="100"
                       autocomplete="off" class="layui-input" readonly="true">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label febs-form-item-require">通知内容</label>
            <div class="layui-input-block">
                <textarea name="content" id="txtContent" maxlength="100"
                          class="layui-textarea" lay-verify="required"></textarea>
            </div>
        </div>
        <div class="layui-form-item">

            <div>
                <label class="layui-form-label">通知视频</label>
                <div class="layui-upload">
                    <div class="layui-upload-list" width="100%">
                        <video class="layui-upload-video" src="" id="videoPlay" controls="controls" style="vertical-align: bottom;width: 35%"  hidden="true">
                        </video>
                        <a onclick="getElementById('fileUpload').click()" style="margin-right: 10px;height: 38px;line-height: 38px;margin-left: 4px;">
                            请选择视频
                            <input type="file" hidden="hidden" id="fileUpload">
                        </a>
                        <input type="hidden" id="videoId">
                        <a id="authUpload"  disabled="true" style="margin-right: 10px"  hidden="true">开始上传</a>
                        <a id="pauseUpload"  disabled="true" style="margin-right: 10px" hidden="true">暂停</a>
                        <a id="resumeUpload"  disabled="true" hidden="true">恢复上传</a>
                        <div class="layui-progress" hidden="hidden"  id="videoProgress" style="margin-left: 110px" lay-filter="videoProgress" lay-showPercent="true" >
                            <div class="layui-progress-bar" lay-percent="0%"  style="width: 0%"></div>
                        </div>
                        <input type="hidden" id="noticeVideo" name="videoUrl">
                        <p id="videoText"></p >
                        <label class="status" style="margin-left: 110px;margin-top: 10px"><span id="status"></span></label>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label febs-form-item-require">通知附件</label>
            <div class="layui-upload">
                <div class="layui-upload-list">
                    <a class='layui-icon layui-icon-file-image' id="file1" target='_blank'
                       data-th-href="${fileurl}">附件</a>
                    <input type="hidden" id="myfile" name="myfile">
                    <p id="fileText"></p>
                </div>
                <a id="testfile">上传附件</a>
            </div>
        </div>
        <div class="layui-row">
            <div class="layui-col-md10">
                <div class="layui-form-item" style="margin-left: 10px">
                    <label class="layui-form-label febs-form-item-require">接收人</label>
                    <div class="layui-input-block">
                        <textarea id="noticereceive" data-th-text="${noticeUserId}" lay-verify="required"
                                  autocomplete="off"
                                  class="layui-textarea" readonly="true"></textarea>
                    </div>
                </div>
            </div>

            <!--隐藏的部分属性-->
            <div class="layui-form-item febs-hide">
                <label class="layui-form-label febs-form-item-require">接收人隐藏id</label>
                <div class="layui-input-block">
                    <input type="text" name="userId" id="noticereceivehide">
                    <input type="text" name="userIdPool" id="noticereceivehidePool">
                </div>
            </div>

        </div>
        <div style="text-align:center" class="layui-form-item febs-hide">
            <input type="button" class="layui-btn" lay-submit="" lay-filter="btnPreservation-submit"
                   id="btnPreservation" value="确定">
            <input type="button" class="layui-btn" lay-submit="" lay-filter="btnDraft-submit" id="btnDraft" value="取消">
        </div>
        <input type="hidden" id="id" name="id" data-th-value="${id}">
    </form>
</div>
<script data-th-inline="javascript" type="text/javascript">
    layui.use(['febs', 'form', 'xmSelect', 'upload', 'validate', 'laydate', 'dropdown', 'jquery', 'table'], function () {
        let $ = layui.$,
            febs = layui.febs,
            layer = layui.layer,
            form = layui.form,
            laydate = layui.laydate,
            dropdown = layui.dropdown,
            jquery = layui.jquery,
            table = layui.table,
            notice = [[${noticeId}]],
            noticePool = [[${noticeIdPool}]],
            noticeVideo = [[${noticevoid}]],
            $view = $('#notice-edit'),
            $student = $view.find('#student'),
            $reset = $view.find('#reset'),
            upload = layui.upload,
            img2 = [[${img}]],
            title = [[${noticeTitle}]],
            noticeContent = [[${noticeContent}]],
            noticefile = [[${fileurl}]],
            validate = layui.validate;

        let lock = false;
        form.verify(validate);
        form.render();

        initCollegeValue();

        function initCollegeValue() {
            if (img2 === "") {
                $('#imgNotice').attr('src', "/febs/images/defaultImg.png");
            } else {
                $('#imgNotice').attr('src', img2);
                $('#notimg').val(img2)
            }
            if(noticeVideo === ""){

            }else {
                $("#videoPlay").attr('src',noticeVideo)
                $("#noticeVideo").val(noticeVideo)
            }
            if (noticefile === ""){

            }else {
                $("#myfile").val(noticefile)
            }
            if (notice != null){
                form.val("notice-edit-form", {
                    "userId": notice,
                });
            }if (noticePool != null){
                form.val("notice-edit-form", {
                    "userIdPool": noticePool,
                });
            }
        }

        $reset.on('click', function () {
            document.getElementById("noticereceive").value = "";

        })

        //回填
        form.val("notice-edit-form", {
            "title": HTMLDecode(title)
            , "content": HTMLDecode(noticeContent)
        });

        //保存草稿
        form.on('submit(btnPreservation-submit)', function (data) {
            if (!lock) {
                lock = true;
                $.ajax({
                    type: 'post',
                    url: 'notice/updateNoticeUser',
                    data: $('#editForm').serialize(),
                    success: function () {
                        layer.closeAll();
                        $('#notice-list').find('#btnReset').click();
                        febs.alert.success('通知修改成功');
                    }
                })
                setTimeout(function () {
                    lock = false;
                }, 800);
            }
        })


        //图片上传
        var uploadInst = upload.render({
            elem: '#imgNotice'
            , url: ctx + 'upload' //改成您自己的上传接口
            , method: 'post'
            , auto: false
            , accept: 'images'
            , exts: 'jpg|png|gif|bmp|jpeg'
            , choose: function (obj) {
                //预读本地文件示例，不支持ie8
                var flag = true;
                obj.preview(function (index, file, result) {
                    var img = new Image();
                    img.src = result;
                    img.onload = function () { //初始化夹在完成后获取上传图片宽高，判断限制上传图片的大小。
                        if (img.width <= 750 && img.height <= 560) {
                            $('#imgNotice').attr('src', result); //图片链接（base64）
                            obj.upload(index, file); //满足条件调用上传方法
                        } else {
                            flag = false;
                            layer.msg("您上传的小图大小必须小于750*560尺寸！");
                            return false;
                        }
                    }
                    return flag;
                });
            }
            , done: function (res) {
                //上传成功
                if (res.code == 200) {
                    layer.msg('上传图片成功');
                    $("#notimg").val(res.url);
                }
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
        });
        //附件上传
        var uploadFile = upload.render({
            elem: '#testfile'
            , url: ctx + 'upload' //改成您自己的上传接口
            , method: 'post'
            , auto: false
            , accept: 'file'
            , exts: 'bmp|jpeg|doc|docx|txt|xlsx|pdf'
            , choose: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#file1').attr('href', result);
                    obj.upload(index, file);
                });
            }
            , done: function (res) {
                //上传成功
                if (res.code == 200) {
                    layer.msg('上传附件成功');
                    $("#myfile").val(res.url);
                }
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#fileText');
                demoText.html('<span style="color: #FF5722;">上传附件失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadFile.upload();
                });
            }
        });

        //文本框内容转义
        function HTMLEncode(html) {
            var temp = document.createElement("div");
            (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
            var output = temp.innerHTML;
            temp = null;
            return output;
        }


        //文本框内容反转义
        function HTMLDecode(text) {
            var temp = document.createElement("div");
            temp.innerHTML = text;
            var output = temp.innerText || temp.textContent;
            temp = null;
            return output;
        }

        //视频上传
        if (!FileReader.prototype.readAsBinaryString) {
            FileReader.prototype.readAsBinaryString = function (fileData) {
                let binary = "";
                let pt = this;
                let reader = new FileReader();
                reader.onload = function (e) {
                    let bytes = new Uint8Array(reader.result);
                    let length = bytes.byteLength;
                    for (let i = 0; i < length; i++) {
                        binary += String.fromCharCode(bytes[i]);
                    }
                    //pt.result  - readonly so assign binary
                    pt.content = binary;
                    pt.onload()
                }
                reader.readAsArrayBuffer(fileData);
            }
        }
        $(document).ready(function () {
            /**
             * 创建一个上传对象
             * 使用 UploadAuth 上传方式
             */
            function createUploader () {
                let uploader = new AliyunUpload.Vod({
                    timeout: 60000,
                    partSize: 10485760,
                    parallel: 2,
                    retryCount: 3,
                    retryDuration: 2,
                    region: "cn-shanghai",
                    userId: "1592141428197506",
                    // 添加文件成功
                    addFileSuccess: function (uploadInfo) {
                        $('#authUpload').attr('disabled', false)
                        $('#resumeUpload').attr('disabled', false)
                        $('#status').text('添加文件成功, 等待上传...')
                    },
                    // 开始上传
                    onUploadstarted: function (uploadInfo) {
                        // 如果是 UploadAuth 上传方式, 需要调用 uploader.setUploadAuthAndAddress 方法
                        // 如果是 UploadAuth 上传方式, 需要根据 uploadInfo.videoId是否有值，调用点播的不同接口获取uploadauth和uploadAddress
                        // 如果 uploadInfo.videoId 有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
                        // 注意: 这里是测试 demo 所以直接调用了获取 UploadAuth 的测试接口, 用户在使用时需要判断 uploadInfo.videoId 存在与否从而调用 openApi
                        // 如果 uploadInfo.videoId 存在, 调用 刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)
                        // 如果 uploadInfo.videoId 不存在,调用 获取视频上传地址和凭证接口(https://help.aliyun.com/document_detail/55407.html)
                        if(uploadInfo.videoId){
                            let refreshUrl =  '/refreshAuth?videoId=' + uploadInfo.videoId
                            $.get(refreshUrl, function (data) {
                                uploader.setUploadAuthAndAddress(uploadInfo, data.uploadAuth, data.uploadAddress);
                            }, 'json')
                        }else {
                            let createUrl =  '/getAuth?title='+ title +'&suffix='+ suffix;
                            $.get(createUrl, function (data) {
                                let uploadAuth = data.uploadAuth
                                let uploadAddress = data.uploadAddress
                                let videoId = data.videoId

                                $("#videoId").val(videoId);

                                uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId)
                            }, 'json')
                            $('#status').text('准备中...')
                        }
                    },
                    // 文件上传成功
                    onUploadSucceed: function (uploadInfo) {
                        $('#status').text('文件上传成功!')
                        $("#videoProgress").attr('hidden','hidden');
                        $("#videoPlay").attr("hidden",false);
                        $('#authUpload').attr("hidden",true);
                        $('#pauseUpload').attr("hidden",true);
                        $('#resumeUpload').attr("hidden",true);

                        let getVideoUrl =  '/getVideoUrl?videoId='+ uploadInfo.videoId;
                        $.get(getVideoUrl, function (data) {
                            videoURL = data[0].playURL;
                            $("#videoPlay").attr("src",videoURL);
                            $("#noticeVideo").val(videoURL);
                        },'json')
                    },
                    // 文件上传失败
                    onUploadFailed: function (uploadInfo, code, message) {
                        $('#status').text('文件上传失败!')
                    },
                    // 取消文件上传
                    onUploadCanceled: function (uploadInfo, code, message) {
                        $('#status').text('文件上传已暂停!')
                    },
                    // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
                    onUploadProgress: function (uploadInfo, totalSize, progress) {
                        let progressPercent = Math.ceil(progress * 100)
                        element.progress('videoProgress',progressPercent+'%');
                        $('#auth-progress').text(progressPercent)
                        $('#status').text('进度...'+progressPercent+'%')
                    },
                    // 上传凭证超时
                    onUploadTokenExpired: function (uploadInfo) {
                        // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
                        // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
                        // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
                        $('#status').text('文件上传超时!')
                        let refreshUrl =  '/refreshAuth?videoId=' + uploadInfo.videoId
                        $.get(refreshUrl, function (data) {
                            let uploadAuth = data.uploadAuth
                            uploader.resumeUploadWithAuth(uploadAuth)
                        }, 'json')
                    },
                    // 全部文件上传结束
                    onUploadEnd: function (uploadInfo) {
                        $('#status').text('文件上传完毕!')
                    }
                })
                return uploader
            }

            let uploader = null

            $('#fileUpload').on('change', function (e) {
                $("#authUpload").attr("hidden",false);
                $("#pauseUpload").attr("hidden",false);
                let file = e.target.files[0]
                if (!file) {
                    febs.alert.warn("请先选择需要上传的文件!")
                    return
                }

                var fileName = file.name.substring(file.name.lastIndexOf(".") ).toLowerCase();
                title = file.name.substring(0,file.name.lastIndexOf("."));
                suffix = fileName;
                if (fileName !== ".mp4" && fileName !== ".M3U8" && fileName !== ".FLV" && fileName !== ".MKV") {
                    febs.alert.warn("请选择MP4、M3U8、FLV、MKV4格式文件上传！");
                    e.target.value ="";
                    return
                }
                let userData = '{"Vod":{}}'
                if (uploader) {
                    uploader.stopUpload()
                    $('#auth-progress').text('0')
                    $('#status').text("")
                }
                uploader = createUploader()
                // 首先调用 uploader.addFile(event.target.files[i], null, null, null, userData)
                uploader.addFile(file, null, null, null, userData)
                $('#authUpload').attr('disabled', false)
                $('#pauseUpload').attr('disabled', true)
                $('#resumeUpload').attr('disabled', true)
            })

            // 第一种方式 UploadAuth 上传
            $('#authUpload').on('click', function () {
                // 然后调用 startUpload 方法, 开始上传
                if (uploader !== null) {
                    uploader.startUpload()
                    $("#videoProgress").attr('hidden',false);
                    $('#authUpload').attr('disabled', true)
                    $('#pauseUpload').attr('disabled', false)
                }
            })

            // 暂停上传
            $('#pauseUpload').on('click', function () {
                if (uploader !== null) {
                    uploader.stopUpload()
                    $('#resumeUpload').attr('disabled', false);
                    $('#pauseUpload').attr('disabled', true);
                    $("#pauseUpload").attr("hidden",false);
                    $("#resumeUpload").attr("hidden",false);
                }
            })

            $('#resumeUpload').on('click', function () {
                if (uploader !== null) {
                    uploader.startUpload()
                    $('#resumeUpload').attr('disabled', true);
                    $('#pauseUpload').attr('disabled', false);
                    $("#pauseUpload").attr("hidden",false);
                    $("#resumeUpload").attr("hidden",false);
                }
            })

        })
    });
</script>